package com.example.carbonbackend.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.carbonbackend.common.BaseResponse;
import com.example.carbonbackend.common.ErrorCode;
import com.example.carbonbackend.common.ResultUtils;
import com.example.carbonbackend.exception.BusinessException;
import com.example.carbonbackend.exception.ThrowUtils;
import com.example.carbonbackend.model.dto.emission.CarbonEmissionAddRequest;
import com.example.carbonbackend.model.dto.emission.CarbonEmissionQueryRequest;
import com.example.carbonbackend.model.entity.Company;
import com.example.carbonbackend.model.entity.CarbonEmission;
import com.example.carbonbackend.model.entity.CompanyUser;
import com.example.carbonbackend.model.entity.User;
import com.example.carbonbackend.model.vo.CarbonEmissionVO;
import com.example.carbonbackend.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("carbonEmission")
@Slf4j
public class CarbonEmissionController {

    @Resource
    CarbonEmissionService carbonEmissionService;
    @Resource
    CompanyService companyService;
    @Resource
    UserService userService;
    @Resource
    CompanyUserService companyUserService;

    /**
     * 传入碳排放数据文件
     */
    @PostMapping()
    public BaseResponse<String> add(String companyName, String year,
                                    String companyStyle,
                                    MultipartFile file) throws IOException {

        log.info("{}{}{}{}", companyName, companyStyle, year, file);
        //查找公司是否存在
        LambdaQueryWrapper<Company> companyLambdaQueryWrapper = new LambdaQueryWrapper<>();
        companyLambdaQueryWrapper.eq(Company::getCompanyName, companyName);
        Company company = companyService.getOne(companyLambdaQueryWrapper);
        if (company == null && company.getIsDelete().equals(1)) {
            ResultUtils.error(404, "公司不存在或公司被删除");
        }
        File userfile = File.createTempFile("temp", null);
        file.transferTo(userfile);
        if (companyStyle.equals("发电企业")) {

            // carbonEmissionService.inputEG(companyName, year, userfile);

            return carbonEmissionService.inputEG(companyName, year, userfile);
        } else if (companyStyle.equals("电网企业")) {
            return carbonEmissionService.inputEU(companyName, year, userfile);
        } else if (companyStyle.equals("电解铝企业")) {
        } else if (companyStyle.equals("民航企业")) {
        }


        return null;
    }

    /**
     * 用户获取碳排放数据
     */
    @GetMapping()
    public BaseResponse<String> seach(@RequestParam String companyName, @RequestParam String year) {
        int iyear;
        try {
            iyear = Integer.parseInt(year);
        } catch (NumberFormatException e) {
            throw new BusinessException("请输入正确年份");
        }
        String url = carbonEmissionService.search(companyName, iyear);
        return ResultUtils.success(url);
    }


    // region 增删改查
//
//    /**
//     * 创建
//     *
//     * @param carbonEmissionAddRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/add")
//    public BaseResponse<Long> addCarbonEmission(@RequestBody CarbonEmissionAddRequest carbonEmissionAddRequest, HttpServletRequest request) {
//        // 判断是否添加记录
//        if (carbonEmissionAddRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        CarbonEmission carbonEmission = new CarbonEmission();
//        BeanUtils.copyProperties(carbonEmissionAddRequest, carbonEmission);
//
//        boolean save = carbonEmissionService.save(carbonEmission);
//
//        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
//
//        return ResultUtils.success(carbonEmission.getBuyerId());
//
//    }


    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CarbonEmissionVO> getCarbonEmissionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CarbonEmission carbonEmission = carbonEmissionService.getById(id);
        if (carbonEmission == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(carbonEmissionService.getCarbonEmissionVO(carbonEmission, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param carbonEmissionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<CarbonEmission>> listCarbonEmissionByPage(@RequestBody CarbonEmissionQueryRequest carbonEmissionQueryRequest) {
        long current = carbonEmissionQueryRequest.getCurrent();
        long size = carbonEmissionQueryRequest.getPageSize();
        Page<CarbonEmission> carbonEmissionPage = carbonEmissionService.page(new Page<>(current, size),
                carbonEmissionService.getQueryWrapper(carbonEmissionQueryRequest));
        return ResultUtils.success(carbonEmissionPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param carbonEmissionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CarbonEmissionVO>> listCarbonEmissionVOByPage(@RequestBody CarbonEmissionQueryRequest carbonEmissionQueryRequest,
                                                                           HttpServletRequest request) {
        long current = carbonEmissionQueryRequest.getCurrent();
        long size = carbonEmissionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<CarbonEmission> carbonEmissionPage = carbonEmissionService.page(new Page<>(current, size),
                carbonEmissionService.getQueryWrapper(carbonEmissionQueryRequest));
        return ResultUtils.success(carbonEmissionService.getCarbonEmissionVOPage(carbonEmissionPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param carbonEmissionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<CarbonEmissionVO>> listMyCarbonEmissionVOByPage(@RequestBody CarbonEmissionQueryRequest carbonEmissionQueryRequest,
                                                                             HttpServletRequest request) {

        if (carbonEmissionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        // 获取用户本身的碳核算记录 用户id->公司id
        QueryWrapper<CompanyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getId());
        CompanyUser companyUser = companyUserService.getOne(queryWrapper);
        carbonEmissionQueryRequest.setCompanyId(companyUser.getCompanyId());
        long current = carbonEmissionQueryRequest.getCurrent();
        long size = carbonEmissionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<CarbonEmission> carbonEmissionPage = carbonEmissionService.page(new Page<>(current, size),
                carbonEmissionService.getQueryWrapper(carbonEmissionQueryRequest));
        log.info("查询信息{}", carbonEmissionQueryRequest);
        log.info("查询结果{}", carbonEmissionPage.getRecords());
        return ResultUtils.success(carbonEmissionService.getCarbonEmissionVOPage(carbonEmissionPage, request));
    }


}
